import axios from 'axios'
import NProgress from 'nprogress'

axios.defaults.baseURL = import.meta.env.VITE_APP_WEB_URL
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.interceptors.request.use(
  (config) => {
    // 请求配置
    return config
  },
  (error) => {
    // 错误处理
    return error
  }
)
axios.interceptors.response.use((res) => {
  // 结果处理
  return res
})

export interface ICommonResponse<T> {
  error_code: number
  data?: T
  message: string
  err?: string
}
interface Http {
  get<T>(url: string, params?: unknown): Promise<ICommonResponse<T>>
  post<T>(url: string, params?: unknown): Promise<ICommonResponse<T>>
}

const http: Http = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .get(url, { params })
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  post(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .post(url, JSON.stringify(params))
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
}
export default http
